import { onMounted, onUnmounted, ref } from 'vue';

export function useSpeechSynthesis() {
  const isSpeaking = ref(false);
  const voices = ref<SpeechSynthesisVoice[]>([]);
  const utterance = ref<SpeechSynthesisUtterance | null>(null);

  // 初始化语音合成器
  const initializeVoices = () => {
    voices.value = window.speechSynthesis.getVoices();
  };

  // 创建新的语音对象
  const createUtterance = (
    text: string,
    lang: string = 'zh-CN',
    voiceIndex: number = 0,
  ) => {
    if (!window.speechSynthesis) {
      console.error('浏览器不支持 speechSynthesis');
      return;
    }

    const newUtterance = new SpeechSynthesisUtterance(text);
    newUtterance.lang = lang;
    newUtterance.voice = voices.value[voiceIndex] || null;

    newUtterance.onstart = () => {
      isSpeaking.value = true;
    };

    newUtterance.onend = () => {
      isSpeaking.value = false;
    };

    utterance.value = newUtterance;
  };

  // 播放语音
  const speak = () => {
    if (utterance.value) {
      window.speechSynthesis.speak(utterance.value);
    }
  };

  // 停止语音
  const stop = () => {
    window.speechSynthesis.cancel();
    isSpeaking.value = false;
  };

  // 初始化语音合成系统
  onMounted(() => {
    if (window.speechSynthesis.onvoiceschanged !== undefined) {
      window.speechSynthesis.onvoiceschanged = initializeVoices;
    }
    initializeVoices();
  });

  // 清理资源
  onUnmounted(() => {
    stop();
  });

  return {
    isSpeaking,
    voices,
    createUtterance,
    speak,
    stop,
  };
}
